﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UpdateForm
{
    public class DataBase
    {
        private static SqlConnection con = null;
        private static SqlCommand cmd = null;
        private static SqlDataAdapter da = null;
        /// <summary>
        /// 获取所有的数据库名称
        /// </summary>
        /// <returns>数据库名称</returns>
        public static DataSet GetDataBase(string constring)
        {
            DataSet ds = null;
            try
            {
                con = new SqlConnection(constring);
                con.Open();
                ds = new DataSet();
                da = new SqlDataAdapter("SELECT Name FROM Master..SysDatabases ORDER BY Name", con);
                da.Fill(ds, "database");
            }
            catch (Exception ex)
            {
                if (con.State == ConnectionState.Connecting || con.State == ConnectionState.Open)
                {
                    con.Close();
                }
                throw ex;
            }
            finally
            {
                if (con.State == ConnectionState.Connecting || con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
            return ds;
        }

        public static string ExecSql(string constring,string sql)
        {
            string ver = "";
            try
            {
                con = new SqlConnection(constring);
                con.Open();
                cmd = con.CreateCommand();
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {

                ver = ex.Message;
            }
            finally
            {
                if (con.State == ConnectionState.Connecting || con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
            return ver;
        }
    }
}
